<template>
<section v-loading="loading">
   <!-- 查询框 -->
   <div class="searchbox">
      <el-form :inline="true" :model="query" class="demo-form-inline fl" @submit.native.prevent>
         <el-form-item>
            <el-input v-model="query.keyword" placeholder="姓名/手机号" size="medium"></el-input>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" size="small" @click="getData" icon="el-icon-search">搜&nbsp;&nbsp;索</el-button>
         </el-form-item>
      </el-form>
      <el-button type="primary" size="small" class="fr" icon="el-icon-plus" @click.stop="add">添加账号</el-button>
   </div>
   <!-- 主体内容 -->
   <div @contextmenu="$parent.addMenu([{name:'刷新账号列表',method:'getData',icon:'icon-shuaxin'}])">
   <el-table ref="multipleTable" :data="listData" highlight-current-row tooltip-effect="dark" style="text-align:center">
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="mobile" label="手机号"></el-table-column>
      <el-table-column prop="create_time" label="创建时间"></el-table-column>
      <el-table-column prop="last_time" label="最后登录时间"></el-table-column>
      <el-table-column prop="last_ip" label="最后登录IP"></el-table-column>
      <el-table-column label="操作">
         <template slot-scope="scope" v-if="scope.row.parentid!=0">
            <span @click.stop="edit(scope.row)" style="color:#67C23A;cursor:pointer">编辑</span>
            <span style="color:#F56C6C;cursor:pointer;margin-left:10px" @click.stop="del(scope.row)">删除</span>
         </template>
      </el-table-column>
   </el-table>
 </div>
   <!-- 分页 -->
   <div class="breakpage" v-if="page.total>0">
      <el-pagination layout="total, prev, pager, next" background :current-page="parseInt(page.curpage)"
         :page-size="parseInt(page.pagesize)" :total="parseInt(page.total)" @current-change="handleCurrentChange" >
      </el-pagination>
   </div>
   <!-- ↓↓编辑弹窗↓↓ -->
   <el-dialog :title="form.type=='add'?'添加账号':'编辑'" :visible.sync="form.show" @close="closeDialog" width="600px">
      <el-form ref="form" :model="form.data" :rules="rules" label-width="70px" style="margin:0 auto">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.data.name" placeholder="请输入管理员姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.data.mobile" placeholder="请输入管理员手机号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="form.data.pwd" :placeholder="form.type=='add'?'请输入密码':'********'"></el-input>
        </el-form-item>
        <el-form-item label="驾校" prop="school_id" v-if="$parent.school.list.length>1">
            <el-select v-model="form.data.school_id" multiple placeholder="请选择管理驾校" style="width:100%">
             <el-option v-for="item in $parent.school.list" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
       </el-form-item>
        <el-form-item label="权限">
          <el-row v-for="(item,index) in menu" :key="index">
            <el-col :span="1">&nbsp;</el-col>
            <el-col :span="5">
                <el-checkbox v-model="form.data.checked" :label="item.id" @change="checkAll(index)">{{item.name}}</el-checkbox>
            </el-col>
            <el-col :span="18">
              <el-checkbox-group v-model="form.data.checked" @change="checkedChange(index)">
                <el-checkbox  v-for="child in item.children" :label="child.id" :key="child.id" style="margin:0 10px 10px 0">{{child.name}}</el-checkbox>
              </el-checkbox-group>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer">
         <el-button size="small" @click="form.show=false">取 消</el-button>
         <el-button size="small" type="primary" @click.stop="submitForm" :loading="form.loading">确 定</el-button>
      </div>
   </el-dialog>
   <!-- ↑↑编辑弹窗↑↑ -->
</section>
</template>

<script>
import * as api from '../api/index'
import {date,getChild,checkMobile} from '../lib/function';
var validateMobile = (rule, value, callback) => {
    if (value==''||value==undefined) {
      callback(new Error('请输入手机号'));
    } else if(!checkMobile(value)){
      callback(new Error('手机号格式不正确'));
    }
    callback();
};
export default {
   name: 'administrator',
   data() {
      return {
         m: 'administrator',
         query: {}, //搜索数据
         form:{
           show:false,
           loading:false,
           type:'add',
           data:{checked:[]}
         },
         menu:[],
         rules: {
            name: [
              {required: true, message: '请输入管理员姓名', trigger: 'blur' }
             ],
            mobile:[
              {required: true, message: '请输入管理员手机号', trigger: 'blur' },
              {validator:validateMobile,trigger: 'blur' },
            ],
            school_id:[
              {required: true, message: '请选择驾校', trigger: 'change' },
            ]
         }
      }
   },
   computed: {
      listData() {
         return this.$store.state[this.m].data;
      },
      page() {
         return this.$store.state[this.m].page;
      },
      loading() {
         return this.$store.state[this.m].loading;
      }
   },
   filters: {date},
   methods: {
     checkAll(index) {
         let checked=this.form.data.checked;
         let isCheck=checked.indexOf(this.menu[index].id);
         if(isCheck==-1) {//取消全选
           this.menu[index].children.forEach(item=>{
              let i=checked.indexOf(item.id);
              if(i!=-1) checked.splice(i,1);
           });
         }else{//全选
           this.menu[index].children.forEach(item=>{
               if(checked.indexOf(item.id)==-1) checked.push(item.id);
           });
         }
     },
     checkedChange(index) {
       let checked=this.form.data.checked;
       let child=this.menu[index].children;
       let isCheck=false;
       let pos=checked.indexOf(this.menu[index].id);
       for(let i in child){
          if(checked.indexOf(child[i].id)!=-1){
             isCheck=true;
             break;
          }
       }
       if(isCheck) pos==-1?checked.push(this.menu[index].id):'';
       else pos!=-1?checked.splice(pos,1):'';
     },
      getData() { //更新列表数据
         this.$store.dispatch(
            this.m + '/getData',
            JSON.parse(JSON.stringify(this.query))
         );
      },
      handleCurrentChange(p){
         this.query.p = p;
         this.getData();
      },
      closeDialog(){
        this.$refs['form'].clearValidate();
      },
      add(){
        this.form.data={checked:[],school_id:[]};
        if(this.$parent.school.list.length>1) this.form.data.school_id=[];
        this.form.type='add';
        this.form.show = true;
      },
      edit(row){
         this.form.show = true;
         this.form.type='edit';
         this.form.data = JSON.parse(JSON.stringify(row));
         this.form.data.school_id=this.form.data.school_id.split(',');
         if(this.form.data.checked=='') this.form.data.checked=[];
         else this.form.data.checked=this.form.data.checked.split(',');
      },
      submitForm(){

        this.$refs['form'].validate((valid) => {
          if(valid){
            this.form.loading=true;
            api.administrator[this.form.type](this.form.data,res => {
              if (res.status == 1) {
                this.form.show = false;
                this.getData();
              }
              else this.$notify(res);
              this.form.loading=false;
            });
          }else return false;
        });
      },
      del(row){
        this.$confirm('确定删除该账号?','提示',{confirmButtonText:'确定',cancelButtonText:'取消',type: 'warning'
          }).then(() => {
            api.administrator.del({id:row.id},res=>{
              if(res.status==1){
                this.getData();
              }else this.$notify(res);
            });
          }).catch(()=>{});
      }
   },
   created() {
      if(this.$parent.school.current.id==undefined||this.$store.state[this.m].school_id!=this.$parent.school.current.id) {
        this.query={};
        this.getData();
        this.$store.commit(this.m+'/update',{type:'school_id',data:this.$parent.school.current.id});
      }else{
        this.query=JSON.parse(JSON.stringify(this.$store.state[this.m].query));
      }
      api.administrator.getNode({},res=>{
          let arr=[];
          res.data.forEach(item=>{
              if(item.parentid==0) {
                item.children=getChild(res.data,item.id);
                arr.push(item);
              }
          });
          this.menu=arr;
      });
   },
    beforeRouteEnter (to, from, next) {
      let admin=JSON.parse(sessionStorage.getItem('user'));
      if(parseInt(admin.parentid)>0){
        alert('只有超级管理员才能访问账户管理');
        next(false);
      }else next();
    }
}
</script>
